package com.fast.orm.exec;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.fast.orm.cache.DataCache;
import com.fast.orm.data.DataPackage;
import com.fast.orm.data.Expression;
import com.fast.orm.jdbc.JdbcImpl;
import com.fast.orm.utils.FastValueUtil;

import java.util.Date;

public class UpdateExecution<T> {
    private final DataPackage dataPackage;

    public UpdateExecution(DataPackage dataPackage) {
        this.dataPackage = dataPackage;
    }

    public Integer updateByPrimaryKey(Comparable<?> primaryKeyValue) {
        if (primaryKeyValue == null) {
            throw new RuntimeException(dataPackage.getTableMapper().getTableName() + ": 主键参数不能为空!!!");
        }
        dataPackage.addWhere(new DataPackage.ConditionData(dataPackage.getTableMapper().getPrimaryKeyField(), primaryKeyValue, DataPackage.Way.AND, Expression.Equal));
        return update();
    }

    public Integer updateByPrimaryKey() {
        DataPackage.UpdateField updateField = dataPackage.getUpdateFieldMap().get(dataPackage.getTableMapper().getPrimaryKeyField());
        if (updateField == null || updateField.getValue() == null) {
            throw new RuntimeException(dataPackage.getTableMapper().getTableName() + ": 主键参数不能为空!!!");
        }
        dataPackage.addWhere(new DataPackage.ConditionData(dataPackage.getTableMapper().getPrimaryKeyField(), updateField.getValue(), DataPackage.Way.AND, Expression.Equal));
        return update();
    }

    public Integer updateOverallByPrimaryKey(Comparable<?> primaryKeyValue) {
        dataPackage.setUpdateOverall(Boolean.TRUE);
        return updateByPrimaryKey(primaryKeyValue);
    }

    public Integer updateOverallByPrimaryKey() {
        dataPackage.setUpdateOverall(Boolean.TRUE);
        return updateByPrimaryKey();
    }

    public Integer update() {
        if (CollUtil.isEmpty(dataPackage.getWhereList())) {
            throw new RuntimeException(dataPackage.getTableMapper().getTableName() + ": 更新操作必须设置条件!!!");
        }
        FastValueUtil.setUpdateTime(dataPackage, new Date());
        Integer updateNum = JdbcImpl.update(dataPackage);
        return updateNum;
    }

    public Integer updateOverall() {
        dataPackage.setUpdateOverall(Boolean.TRUE);
        return update();
    }
}
